package com.example.caorl.jdbcaop.util;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;

public class ConnectionUtils {
    private ThreadLocal<Connection> t = new ThreadLocal<Connection>();
    private DataSource dataSource;

    public void setDataSource(DataSource dataSource) {
        this.dataSource = dataSource;
    }
    public Connection getConnection(){
        try {
            //先从线程上获取
            Connection conn = t.get();
            //判断当前线程上是否有链接
            if(conn==null){
                //从数据源中获取一个链接，并且存入线程中
                conn = dataSource.getConnection();
                t.set(conn);
            }
            return conn;
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
    //把连接和线程解绑
    public void removeConnection(){
        t.remove();
    }
}

